package com.bnz.servlet;

import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.bnz.pojo.Classes;
import com.bnz.service.ClassesService;
import com.bnz.service.impl.ClassesServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

@WebServlet("/classes")
public class ClassesServlet extends HttpServlet {

    private ClassesService classesService;

    @Override
    public void init() throws ServletException {
        classesService = new ClassesServiceImpl();
    }

    /**
     * 1. 根据请求参数调用不同的方法
     * @param req
     * @param resp
     * @throws ServletException
     * @throws IOException
     */
    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //1.1 设置响应结果
        resp.setContentType("text/html;charset=utf8");
        //1.2 得到cmd参数
        String cmd = req.getParameter("cmd");
        //1.3 根据参数名调用不同的方法
        if (StrUtil.isNotBlank(cmd)){
            if ("list".equals(cmd)){
                list(req,resp);
            }
        }
    }

    /**
     * 2. 查询所有班级
     * @param req
     * @param resp
     */
    private void list(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        //2.1 查询所有班级
        List<Classes> classes = classesService.findAll();
        //2.2 转换为字符串并输出
        resp.getWriter().println(JSON.toJSONString(classes));
        //2.3 刷新页面
        resp.getWriter().flush();
    }
}
